package ar.uba.fi.RSACryptoFiuba.model.keygeneration;

import ar.uba.fi.RSACryptoFiuba.model.InvalidValueException;
import ar.uba.fi.RSACryptoFiuba.model.RSACalculator;
import ar.uba.fi.RSACryptoFiuba.model.RSAMessage;
import ar.uba.fi.RSACryptoFiuba.model.RSAStep;

public class CalculatePhiStep extends RSAStep {
	
	@Override
	public void execute(RSAMessage message) {
		RSAKeyGenerationMessage keyGenerationMessage = (RSAKeyGenerationMessage) message;
		Integer p = Integer.valueOf(keyGenerationMessage.getP());
		Integer q = Integer.valueOf(keyGenerationMessage.getQ());
		Integer phi =  RSACalculator.multiply(p-1, q-1);
		keyGenerationMessage.setPhi(phi.toString());
	}
	
	@Override
	public void undo(RSAMessage message) {
		RSAKeyGenerationMessage keyGenerationMessage = (RSAKeyGenerationMessage) message;
		keyGenerationMessage.setPhi("");
	}

	@Override
	public void test(RSAMessage message) {
		String element = message.getElementToEvaluate();
		verifyNumericalValue(element);
		RSAKeyGenerationMessage keyGenerationMessage = (RSAKeyGenerationMessage) message;
		Integer p = Integer.valueOf(keyGenerationMessage.getP());
		Integer q = Integer.valueOf(keyGenerationMessage.getQ());
		Integer phi =  RSACalculator.multiply(p-1, q-1);
		boolean isValid = String.valueOf(phi).equals(element);
		if(!isValid){
			throw new InvalidValueException("El número phi debe ser igual a (p-1)*(q-1).");
		}
		keyGenerationMessage.setPhi(element);
	}

}
